package com.iussoft.gateway.exception;

import com.apache.method.SystemRunnable;
import com.apache.tools.StrUtil;
import com.iussoft.tools.HttpService;

import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

/**
 * @description: 日志写入线程
 * @author: Hou Dayu
 * @date: Created in 2020/9/8
 */
public class LogWritRunable extends SystemRunnable {

    private String message;
    private String levelStr;
    private String indexName;
    private String reqUrl;

    public LogWritRunable(String message, String levelStr, String indexName,String reqUrl){
        this.message = message;
        this.levelStr = levelStr;
        this.indexName = StrUtil.doNull(indexName,"data-warn");
        this.reqUrl = reqUrl;
    }

    @Override
    public void run() {
        try {
            StringBuilder sb = new StringBuilder("http://");
            if(reqUrl.indexOf(",")>-1){
                String[] str = reqUrl.split(",");
                Random rand = new Random();
                int num = rand.nextInt(str.length);
                sb.append(str[num]);
            } else{
               sb.append(reqUrl);
            }
            sb.append("/write/"+indexName+"?levelStr="+levelStr);
            Map<String,String> headParams = new HashMap();
            headParams.put("logMessage", URLEncoder.encode(message, "UTF-8"));
            HttpService.sendPostHttp(sb.toString(),null, headParams);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
